<template>
  <div class="root">
    <el-card>
      <template #header>
        原生的文件上传
      </template>
      <input type="file" ref="file" @change="doUpload"><button
        onclick="this.previousElementSibling.click();">上传图片</button>
      <el-image
        style="width: 200px; height: 200px;border: solid 2px #FFF; margin: 10px; box-shadow: 0 0 5px rgba(0,0,0,.5); display: block;"
        :src="imgPreview" :preview-src-list="[imgPreview]" fit="contain" />
      <div>图片地址：{{ imgPreview }}</div>
      <ol>
        <li>点击按钮的时候触发相邻的上一个元素的点击事件（原生js）</li>
        <li>file域点击事件会打开文件选择框,选择文件后会触发change事件</li>
        <li>绑定file域的change事件，处理上传</li>
      </ol>
    </el-card>

    <el-card>
      <template #header>
        el-upload照片墙案例
      </template>
      <el-upload v-model:file-list="fileList" action="/api/sys/upload" list-type="picture-card" 
      :data="{
        pre: 'imgs',
        watermark: true,
        maxWidth: 1000,
        maxHeight: 1000
      }" 
      :headers="{ 'x-token': store.token }" 
      accept="image/*"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      
      >

        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <pre>{{JSON.stringify(fileList,null," ")}}</pre>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";

import { ElMessage } from "element-plus";
import { userStore } from "@/store/user";
import ajax from "@/api/ajax";

const store = userStore();

//原生的文件上传
const file = ref(null);//获取file域
let imgPreview = ref("");//预览的图片数据
const doUpload = () => {//文件上传处理
  if (file.value.files.length == 0) {//如果没有选择文件，则不做处理
    return;
  }
  let f = file.value.files[0];//获取第一个文件
  file.value.value = "";//清空选择的文件域
  console.debug(f);//控制台日志输出文件对象

  //上传之前根据需要验证文件
  if (!f.type.startsWith == "image/") {
    ElMessage.error("选择的文件必须为图片");
    return;
  }
  if (f.size > 1024 * 1024 * 10) {
    ElMessage.error("选择的文件不能大于10MB");
    return;
  }

  //图片预览
  imgPreview.value = window.URL.createObjectURL(f);
  console.debug(imgPreview);

  let formData = new FormData();
  formData.append("file", f);//上传的文件
  formData.append("pre", "file");//保存路径前缀,默认:file
  formData.append("watermark", "true");//是否加水印,默认:true
  formData.append("maxWidth", 800);//图片最大宽,上传图片大于最大宽,按比例缩小到最大宽
  formData.append("maxHeight", 800);//图片最大高

  //为了看到imgPreview的变化，5秒后再上传
  window.setTimeout(() => {
    ajax.post("/sys/upload/image", formData).then(r => {
      if (r.data.ok) {
        ElMessage.success("上传图片成功");
        imgPreview.value = r.data.data;//设置到预览图片
      }
    });
  }, 5000);

}


//el-upload照片墙案例

const fileList = ref([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
  },
]);

//请求发送成功后
const handleSuccess = (response,uploadFile,uploadFiles)=>{
  console.debug(response,uploadFile,uploadFiles);
  if(response.ok){
    ElMessage.success(`[${uploadFile.name}]上传成功`);
    //额外还要做点什么？
  }else{
    ElMessage.error(`[${uploadFile.name}]上传失败:${response.message}`);
    uploadFiles.pop();//上传失败，移除最后一条上传记录
  }
}
//点击预览
const handlePreview = (uploadFile)=>{
  console.debug(uploadFile);
}




/**
 * 组件挂载事件
 */
onMounted(() => {

});

</script>

<style  scoped>
.root {
  padding: 5rem;
}

.root>* {
  margin-bottom: 5rem;
}
</style>